//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/practice_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/practice/del_collect_enum.dart';
import 'package:hktk_app/model/practice/practice_model.dart';
import 'package:hktk_app/model/practice/practice_section_model.dart';
import 'package:hktk_app/pages/question/record_question_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';

/// 小测日记页面
class DiaryPage extends StatefulWidget {
  const DiaryPage({super.key});

  @override
  State<DiaryPage> createState() => _DiaryPageState();
}

class _DiaryPageState extends State<DiaryPage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据方法
  late List<PracticeSectionModel> _list;

  @override
  void initState() {
    super.initState();
    debugPrint("diaryPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("diaryPage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("diaryPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Column(
        children: [
          PageTitleWidget(name: "小测日记", pageContext: context),
          Expanded(child: _futureData()),
        ],
      ),
    );
  }

  /// 加载数据方法
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
        BuildContext context,
        AsyncSnapshot<Map<String, dynamic>> snapshot,
      ) {
        if (snapshot.connectionState == ConnectionState.done) {
          // 加载完成
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      List<PracticeSectionModel> modelList = await PracticeDao.sectionPractice(
        categoryId: dataUtilComm.dataModel.categoryId,
      );
      // 循环剔除空日期
      for (PracticeSectionModel model in modelList) {
        if (model.data != null) {
          _list.add(model);
        }
      }

      map["suc"] = true;
    } catch (e) {
      debugPrint("diaryPage 页面 -> 获取每日一练记录发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("diaryPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示方法
  _content() {
    return Column(
      children: [
        _tipsItem(),
        Expanded(
          child: SlidableAutoCloseBehavior(
            child: _listItem(),
          ),
        ),
      ],
    );
  }

  /// 提示组件
  _tipsItem() {
    return Container(
      width: MediaQuery.of(_context).size.width,
      height: 54,
      color: colorWhite1,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
        color: colorYellow4,
        child: Text(
          "注意:随机小测日记只会保留最近十天的哦",
          style: FontUtil.fontYellow1(24),
        ),
      ),
    );
  }

  /// 内容显示
  _listItem() {
    if (_list != []) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _list.length,
        ),
      );
    } else {
      // 暂无数据
      return showNoData();
    }
  }

  /// 滑动内容显示方法
  Widget? _itemBuilder(BuildContext context, int index) {
    PracticeSectionModel model = _list[index];
    return _recordItem(model);
  }

  /// 记录item
  Widget _recordItem(PracticeSectionModel model) {
    return Slidable(
      key: ValueKey(model.data!.id!),
      // 把所有item归类到一个组, 保证同时只出现一个滑动的效果
      groupTag: "record",
      // 用户可以拖动的方法
      direction: Axis.horizontal,
      // 滑动动作
      endActionPane: ActionPane(
        // 控制滑动项widget的大小
        extentRatio: 0.16,
        // 滑动效果
        motion: const DrawerMotion(),
        // 滑动出来的内容
        children: _deleteItem(model),
      ),
      // 显示内容
      child: _showItem(model),
    );
  }

  /// 显示的组件
  _showItem(PracticeSectionModel model) {
    return Container(
      width: MediaQuery.of(_context).size.width,
      height: 208,
      padding: EdgeInsets.all(30),
      decoration: BoxDecoration(
        color: colorWhite1,
        border: Border(bottom: BorderSide(color: colorBlack5, width: 1)),
      ),
      child: GestureDetector(
        onTap: () {
          _onTapFunDj(model.data!);
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SvgPicture.asset(
              "images/question/diary_record.svg",
              width: 108,
              height: 148,
            ),
            _showTitle(model),
          ],
        ),
      ),
    );
  }

  /// 标题显示
  _showTitle(PracticeSectionModel model) {
    return SizedBox(
      width: 562,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            model.data!.name!,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: FontUtil.fontBlack1(30, fontWeight: FontWeight.w500),
          ),
          hiSpace(height: 16),
          _bottomTitle(_getZql(model.data!), model.date),
        ],
      ),
    );
  }

  /// 计算正确率，现在显示总题数
  int _getZql(PracticeModel data) {
    return data.qcount ?? 0;
  }

  /// 标题底部显示
  _bottomTitle(zql, sj) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          "总题数：$zql",
          style: FontUtil.fontGrey1(26),
        ),
        Text(
          sj,
          style: FontUtil.fontGrey1(24),
        ),
      ],
    );
  }

  /// 删除组件
  _deleteItem(PracticeSectionModel model) {
    return [
      SlidableAction(
        onPressed: (BuildContext context) {
          _onTapFunSc(model);
        },
        backgroundColor: colorRed5,
        foregroundColor: colorWhite1,
        icon: Icons.delete,
        label: "删除",
        padding: EdgeInsets.symmetric(vertical: 30, horizontal: 24),
      )
    ];
  }

  /// 组件记录被点击
  _onTapFunDj(PracticeModel model) {
    debugPrint('diaryPage 页面 -> 你点击了记录 ===> ');
    // 跳转对应页面
    Navigator.pushNamed(context, "/records-question",
        arguments: {"practiceModel": model});
  }

  /// 删除点击
  _onTapFunSc(PracticeSectionModel model) {
    debugPrint("diaryPage 页面 -> 你点击了删除 ===> ");
    ToastUtil.showDialogBox(
      context: _context,
      contentText: "该操作不可撤销，是否确定删除？",
      contentStyle: FontUtil.fontRed2(30, fontWeight: FontWeight.w500),
      btnLeftText: "取消",
      btnLeftTextColor: colorGrey2,
      btnRightText: "删除",
      btnRightBackgroundColor: colorRed2,
    ).then((value) {
      debugPrint("diaryPage 页面 -> 删除对话框返回值 ===> $value");
      if (value == true) {
        _deleteLoad(model);
      }
    });
  }

  /// 删除加载框
  void _deleteLoad(PracticeSectionModel model) {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 发起请求
    _futureDeleteRecord(model).then((Map<String, dynamic> map) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      if (map["suc"]) {
        setState(() {
          _list.remove(model);
        });
      } else {
        ToastUtil.show(context: _context, msg: map["msg"]);
      }
    });
  }

  /// 删除每日记录相关请求
  Future<Map<String, dynamic>> _futureDeleteRecord(
      PracticeSectionModel model) async {
    Map<String, dynamic> map = {};
    try {
      var userInfo = getUserInfo();
      debugPrint("diaryPage 页面 -> userID ===> ${userInfo.id}");
      debugPrint("diaryPage 页面 -> sss ===> ${userInfo.toJson()}");

      // 先清除记录
      await PracticeDao.delChapterCollect(
        industryCode: dataUtilComm.dataModel.industryId,
        examId: dataUtilComm.dataModel.examId,
        categoryId: dataUtilComm.dataModel.categoryId,
        collectId: model.data!.id!,
        recordsType: CtEnum.everyday,
        type: DelCollectEnum.all,
        haveCollect: true,
      );

      // 发送删除请求
      await PracticeDao.everyDayDelete(id: model.data!.id!);

      map["suc"] = true;
    } catch (e) {
      debugPrint("diaryPage 页面 -> 删除记录请求发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("diaryPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }
}
